<?php
/**
 * 订单商品库存占用明细
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/3/2
 * Time: 9:30
 */
namespace App\Services\Warehouse;
use App\Events\EventConsignmentNote;
use App\Events\EventOrderGoodsInventoryCarryingDetail;
use App\Repositories\Warehouse\OrderGoodsInventoryCarryingDetailRepository;
use App\Services\Orders\OrderService;
use App\Services\Warehouse\ConsignmentNoteService;
use App\Services\Warehouse\WarehouseLocalService;
use PHPUnit\Runner\Exception;

class OrderGoodsInventoryCarryingDetailService extends PublicService{
    protected $OrderGoodsRepository;
    protected $ConsignmentNoteService;//发货通知单
    protected $WarehouseLocalService;
    protected $OrderService;
    public function __construct(OrderGoodsInventoryCarryingDetailRepository $orderGoodsRepository,ConsignmentNoteService $consignmentNoteService,WarehouseLocalService $warehouseLocalService,OrderService $orderService)
    {
        parent::__construct('', false);
        $this->OrderGoodsRepository=$orderGoodsRepository;
        $this->ConsignmentNoteService=$consignmentNoteService;
        $this->WarehouseLocalService=$warehouseLocalService;
        $this->OrderService=$orderService;
    }

    /**
     * 新增订单商品库存占用明细
     * 参数说明
     * order_id  订单ID
        order_sn 订单号
        message_queue_id  消息队列ID
        action  行为状态   默认占用1    1-占用   2-释放
        consignment_note_sn  发货通知单号
        goods_id 商品ID
        goods_sn  商品货号
        wid   仓库ID
        k3_number  金蝶仓库编号
        k3_positions  金蝶仓位
        order_number 订购数量   默认为0
        actual_occupancy_num  实际占用数  默认为0
        add_time  创建时间
        update_time  更新时间
        o_status  状态  默认0（0-未提交，1-未占用，2-已占用，3-占用异常，4-占用失败，5-未释放，6-已释放，7-释放失败，8-释放异常）
    */
    public function AddOrderGoodsInventoryCarryingDetail($AddData){
        if(!is_array($AddData)){
            return false;
        }
        if(empty($AddData['message_queue_id'])){
            $AddData['message_queue_id']=0;
        }
        if(empty($AddData['action'])){
            $AddData['action']=1;
        }
        $AddData['consignment_note_sn'] =  $AddData['consignment_note_sn']??'';
        $AddData['k3_positions']=$AddData['k3_positions']??'';
        if(empty($AddData['order_number'])){
            $AddData['order_number']=0;
        }
        if(empty($AddData['actual_occupancy_num'])){
            $AddData['actual_occupancy_num']=0;
        }
        if(empty($AddData['o_status'])){
            $AddData['o_status']=0;
        }
        $time=time();
        $data=[
            'order_id'=>$AddData['order_id'],
            'order_sn'=>$AddData['order_sn'],
            'message_queue_id'=>$AddData['message_queue_id'],
            'action'=>$AddData['action'],
            'consignment_note_sn'=>$AddData['consignment_note_sn'],
            'goods_id'=>$AddData['goods_id'],
            'goods_sn'=>$AddData['goods_sn'],
            'wid'=>$AddData['wid'],
            'k3_number'=>$AddData['k3_number'],
            'k3_positions'=>$AddData['k3_positions'],
            'order_number'=>$AddData['order_number'],
            'actual_occupancy_num'=>$AddData['actual_occupancy_num'],
            'add_time'=>$time,
            'update_time'=>$time,
            'o_status'=>$AddData['o_status']
        ];
        return $this->OrderGoodsRepository->AddOrderGoodsInventoryCarryingDetail($data);
    }

    /**
     *   根据订单ID或者订单编号来查询该笔订单商品库存占用明细
     *  参数说明（二选一）
     *  order_id  订单ID
     *  order_sn  订单号
     */
    public function GetOrderGoodsInventoryCarryingDetail($WhereData){
        $data=[
            'order_id'=>$WhereData['order_id'],
            'order_sn'=>$WhereData['order_sn']
        ];
        return $this->OrderGoodsRepository->GetOrderGoodsInventoryCarryingDetail($data);
    }

    /**
    *  更新行为状态   默认占用1    1-占用   2-释放
     */
    public function UpdateAction($Id,$Action=1){
        if(empty($Id)){
            return false;
        }
        return $this->OrderGoodsRepository->UpdateAction($Id,$Action);
    }

    /**更新状态  默认0（0-未提交，1-未占用，2-已占用，3-占用异常，4-占用失败，5-未释放，6-已释放，7-释放失败，8-释放异常*/
    public function  UpdateO_status($Id,$O_status=0){
        if(empty($Id)){
            return false;
        }
        return $this->OrderGoodsRepository->UpdateO_status($Id,$O_status);
    }

    /**
     *   根据订单ID或者订单编号来批量修改该笔订单商品库存占用明细的行为状态
     *  默认占用1    1-占用   2-释放
     *  参数说明（二选一）
     *  order_id  订单ID
     *  order_sn  订单号
     *
     *  action  行为状态
     */
    public function UpdateActionBatch($WhereData){
        $data=[
            'order_id'=>$WhereData['order_id']?$WhereData['order_id']:'',
            'order_sn'=>$WhereData['order_sn']?$WhereData['order_sn']:'',
            'action'=>$WhereData['action']
        ];
        return $this->OrderGoodsRepository->UpdateActionBatch($data);
    }

    /**
     *   根据订单ID或者订单编号来批量修改该笔订单商品库存占用明细的行为状态
     *
     *  参数说明（二选一）
     *  order_id  订单ID
     *  order_sn  订单号
     *
     *  o_status  状态  默认0（0-未提交，1-未占用，2-已占用，3-占用异常，4-占用失败，5-未释放，6-请求失败 7-请求异常  8-已释放，9-释放失败，10-释放异常）
     */
    public function UpdateO_statusBatch($WhereData){
        if(empty($WhereData['order_id'])){
            $WhereData['order_id']='';
        }
        if(empty($WhereData['order_sn'])){
            $WhereData['order_sn']='';
        }
        $data=[
            'order_id'=>$WhereData['order_id'],
            'order_sn'=>$WhereData['order_sn'],
            'o_status'=>$WhereData['o_status']
        ];
        return $this->OrderGoodsRepository->UpdateO_statusBatch($data);
    }

    /**
    *  提交未占用的订单商品明细
     */
    public function SubmitNotOccupationK3($Action=1,$Status=1){
        $ListData=$this->OrderGoodsRepository->GetActionAndStatusListGroup($Action,$Status);
        if($ListData){
            $PostSaveData=array();
            foreach ($ListData as $key=>$goodsData){
                $PostSaveData[]=[
                    'order_sn'=>$key
                ];
                foreach ($goodsData as $k=>$v){
                    $PostSaveData['GoodsData'][]=[
                        'goods_sn'=>$v['goods_sn'],
                        'spec_unit'=>$v['spec_unit'],
                    ];
                }
            }
        }else{
            return false;
        }
    }


    /**
     *  提交占用订单商品库存请求
    */
    public function SubmitOrderGoodsInventoryRequest($OrderGoodsData){
        $OrderInfo=array();
        $OrderInfo['order_id']=$OrderGoodsData['order_id'];
        $OrderInfo['order_sn']=$OrderGoodsData['order_sn'];
        $OrderInfo['wid']=$OrderGoodsData['wid'];
        $StockNubmer=$this->WarehouseLocalService->CheckWarehouseBindingExist($OrderGoodsData['wid']);
        $OrderInfo['k3_number']=$StockNubmer;
        $order_goods=array();
        if($OrderGoodsData['GoodsData']){
            $cndata=[
                'order_id'=>$OrderGoodsData['order_id'],
                'order_sn'=>$OrderGoodsData['order_sn'],
                'freight'=>$OrderGoodsData['freight'],
                'discountamount'=>$OrderGoodsData['discountamount']
            ];
            foreach ($OrderGoodsData['GoodsData'] as $key=>$val){
                $order_goods[]=[
                    'goods_id'=>$val['goods_id'],
                    'goods_sn'=>$val['goods_sn'],
                    'goods_number'=>$val['goods_number']
                ];
                $cndata['GoodsData'][]=[
                    'goods_sn'=>$val['goods_sn'],
                    'spec_unit'=>$val['spec_unit'],
                    'best_time'=>$val['best_time'],
                    'goods_number'=>$val['goods_number'],
                    'StockNubmer'=>$StockNubmer,
                    'k3_supplier_sn'=>$val['k3_supplier_sn'],
                    'k3_vmi'=>$val['k3_vmi'],
                    'giving'=>$val['giving'],
                    'goods_price'=>$val['goods_price']
                ];
                $data=[
                    'order_id'=>$OrderInfo['order_id'],
                    'order_sn'=>$OrderInfo['order_sn'],
                    'goods_id'=>$val['goods_id'],
                    'goods_sn'=>$val['goods_sn'],
                    'wid'=>$OrderInfo['wid'],
                    'order_number'=>$val['goods_number'],
                    'k3_number'=>$OrderInfo['k3_number']
                ];
                //新增订单商品库存占用流水
                $this->AddOrderGoodsInventoryCarryingDetail($data);
                unset($data);
            }
        }

        $OrderInfo['order_goods']=$order_goods;
            //新增订单商品库存占用流水
        event(new EventOrderGoodsInventoryCarryingDetail($OrderInfo));
                //提交发货通知单队列中，等待处理
                //event(new EventConsignmentNote($cndata));

        $returnCNdata=$this->ConsignmentNoteService->SaveConsignmentNote($cndata);
         if(!empty($returnCNdata['Id'])){
             $ordergoods=$cndata['GoodsData'];
              if($ordergoods){
                //订单绑定金蝶发货通知单编号
              $this->OrderService->UpdateOrderk3cn_sn($OrderGoodsData['order_id'],$returnCNdata['Number']);
               foreach ($ordergoods as $k=>$v){
                            $updata=[
                                'order_id'=>$OrderGoodsData['order_id'],
                                'goods_sn'=>$v['goods_sn'],
                                'consignment_note_sn'=>$returnCNdata['Number'],
                                'goods_number'=>$v['goods_number']
                            ];
                            $this->UpdateOGICData($updata);
                            unset($updata);
                }
                $data=[
                            'order_id'=>$OrderGoodsData['order_id'],
                            'o_status'=>2
                ];
                $this->UpdateO_statusBatch($data);
                return true;
                }else{
                        $data=[
                            'order_id'=>$OrderGoodsData['order_id'],
                            'o_status'=>3
                        ];
                        $this->UpdateO_statusBatch($data);
                        return false;
                    }
                }else{
                    $data=[
                        'order_id'=>$OrderGoodsData['order_id'],
                        'o_status'=>4
                    ];
                    $this->UpdateO_statusBatch($data);
                    return false;
                }
    }

    /**
    *  根据订单ID和商品货号，来修改绑定金蝶发货通知单单号，以及实际占用数，更新时间
     */
    public function UpdateOGICData($updata){
        $data=[
            'order_id'=>$updata['order_id'],
            'goods_sn'=>$updata['goods_sn'],
            'consignment_note_sn'=>$updata['consignment_note_sn'],
            'goods_number'=>$updata['goods_number']
        ];
        return $this->OrderGoodsRepository->UpdateOGICData($data);
    }

    /**
     *  订单取消处理发货通知
     * @param $order_sn
     * @param $cn_sn
     */
    public function DisposeConsignmentNote($order_sn,$cn_sn){
        $updata=[
            'order_sn'=>$order_sn,
            'action'=>2,//释放
            'o_status'=>5   //未释放
        ];
        //根据订单编号来批量修改该笔订单商品库存占用明细的行为状态
        $this->OrderGoodsRepository->UpdataActionAndO_statusBatch($updata);
        $cninfo=$this->ConsignmentNoteService->GetOrderSnConsignmentNote($cn_sn);
        if(count($cninfo)>0){
            return $cninfo;
        }else{
            return false;
        }
    }

    /***
     * @author echa
     */
    public function UpdataActionAndO_statusBatch(array $data){
        return $this->OrderGoodsRepository->UpdataActionAndO_statusBatch($data);
    }

    public function UsersHandOrderCancel(array $data){

    }
}